package edu.unlv.cs.ladders.entities;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.ManyToMany;
import javax.persistence.Query;
import javax.persistence.UniqueConstraint;
import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;

@Entity
@RooJavaBean
@RooToString
@UniqueConstraint(columnNames = { "value" })
@RooEntity(finders = { "findUserRolesByValue", "findUserRolesByValueEquals" })
public class UserRole extends BaseEntity {

	private static final long serialVersionUID = 1L;

	public static final String ROLE_PARTICIPANT = "ROLE_PARTICIPANT";

    public static final String ROLE_COORDINATOR = "ROLE_COORDINATOR";

    public static final String ROLE_ADMIN = "ROLE_ADMIN";
    
    public static final String ROLE_ANONYMOUS = "ROLE_ANONYMOUS";
    
    private static UserRole ADMIN;
    private static UserRole COORDINATOR;
    private static UserRole PARTICIPANT;
    private static UserRole ANONYMOUS;

    private String value;

    @ManyToMany
    private Set<Participant> users;

    public void addParticipant(Participant participant) {
    	if(!this.getUsers().contains(participant)){
            this.users.add(participant);
    		this.merge();
    	}
    }
    
    public Set<Participant> getUsers(){
    	if(this.users==null){
    		this.users = new HashSet<Participant>();
    	}
    	return this.users;
    }

    public static UserRole getAdminRole() {
        if(ADMIN==null){
        	ADMIN = getRole(ROLE_ADMIN);
        }
        return ADMIN;
    }

    public static UserRole getCoordinatorRole() {
    	if(COORDINATOR==null){
    		COORDINATOR=getRole(ROLE_COORDINATOR);
    	}
        return COORDINATOR;
    }

    public static UserRole getParticipantRole() {
    	if(PARTICIPANT==null){
    		PARTICIPANT=getRole(ROLE_PARTICIPANT);
    	}
        return PARTICIPANT;
    }
    
    public static UserRole getAnonymousRole(){
    	if(ANONYMOUS==null){
    		ANONYMOUS = getRole(ROLE_ANONYMOUS);
    	}
    	return ANONYMOUS;
    }

    private static UserRole getRole(String value) {
        UserRole role;
    	Query query = UserRole.findUserRolesByValue(value);
        role = (UserRole) query.getSingleResult();
        return role;
    }
}
